<template>
  <div class="user-management-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="12">
        <el-form inline :model="queryForm" @submit.prevent>
          <el-form-item>用户列表({{ total }})条&nbsp;&nbsp;</el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.keyword"
              clearable
              maxlength="30"
              placeholder="请输入用户名"
              @input="(e) => (queryForm.keyword = validForbid(e))"
            />
          </el-form-item>
          <el-form-item>
            <el-button :icon="Search" type="primary" @click="queryData">
              查询
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <el-button
          :icon="Plus"
          type="primary"
          @click="handleEdit($event)"
        >
          添加
        </el-button>
        <el-button
          :icon="Delete"
          type="danger"
          @click="handleDelete($event)"
        >
          删除
        </el-button>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      ref="multipleTableRef"
      v-loading="listLoading"
      :data="list"
      highlight-current-row
      row-key="id"
      stripe
      @select="selSingle"
      @select-all="selectAll"
    >
      <el-table-column
        align="left"
        :reserve-selection="true"
        :selectable="checkSelect"
        show-overflow-tooltip
        type="selection"
      />
      <el-table-column align="left" label="序号" min-width="50">
        <template #default="{ $index }">
          {{ $index + 1 + (queryForm.page - 1) * queryForm.pageSize }}
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        label="用户名"
        min-width="140"
        prop="name"
        show-overflow-tooltip
      >
      <template #default="{ row }">
          <span>{{row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        label="手机"
        min-width="140"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span>{{row.tel }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        label="邮箱"
        min-width="140"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span>{{ row.email }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        label="所属部门"
        min-width="140"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <span>{{ deptIdMap[row.deptId] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="left"
        label="操作"
        show-overflow-tooltip
        width="200"
      >
        <template #default="{ row }">
         
          <el-tooltip
            class="item"
            content="编辑"
            effect="light"
            placement="bottom"
          >
            <span
              @click="handleEdit(row)"
            >
              <svg aria-hidden="true" class="icon listIcon">
                <use xlink:href="#icon-bianji" />
              </svg>
            </span>
          </el-tooltip>
          <el-tooltip
            class="item"
            content="删除"
            effect="light"
            placement="bottom"
          >
            <span
              @click="handleDelete(row)"
            >
              <svg aria-hidden="true" class="icon listIcon">
                <use xlink:href="#icon-shanchu" />
              </svg>
            </span>
          </el-tooltip>
          <el-tooltip
            class="item"
            content="重置密码"
            effect="light"
            placement="bottom"
          >
            <span
              @click="handleResetDialog(row)"
            >
              <svg aria-hidden="true" class="icon listIcon">
                <use xlink:href="#icon-A" />
              </svg>
            </span>
          </el-tooltip>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty class="vab-data-empty" description="暂无数据" />
      </template>
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.page"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="editRef" @fetch-data="fetchData" />
    <pwd-set ref="pwdSetRef" />
  </div>
</template>

<script lang="ts">
  import { getUserList, delUser } from '@/api/system/user'
  import {getAllList } from '@/api/depart'
  import { Delete, Plus, Search } from '@element-plus/icons-vue'
  import Edit from './components/UserEdit.vue'
  import PwdSet from './components/PwdSet.vue'
  import {Base64} from 'js-base64'
  import { ElMessage, ElMessageBox } from 'element-plus'
  // import aes from '@/utils/aes.js'
  // const Base64 = require('js-base64').Base64
  export default defineComponent({
    name: 'UserManagement',
    components: {
      Edit,
      PwdSet,
    },
    setup() {
      // const editRef=ref<any>(null)
      // const pwdSetRef=ref<any>(null)
      const state = reactive({
        editRef: null,
        pwdSetRef: null,
        list: [],
        listLoading: false,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        multipleTableRef: null,
        queryForm: {
          page: 1,
          pageSize: 10,
          keyword: '',
        },
        selectRows: [],
        deptIdMap:{},
        allDeptData:[],
      })
      const getAllDept=async()=>{
  getAllList().then(res => {
    state.allDeptData=res.data||[]
    state.allDeptData.forEach(one=>{
      state.deptIdMap[one.id]=one.name
    })
    console.log(state.allDeptData,"~~allDeptData~~~allDeptData~~~")
   })
}
      const selSingle = (selection, row) => {
        if (selection.length > 0) {
          selection.forEach((row) => {
            if (row) {
              if (state.selectRows.indexOf(row.id) === -1) {
                state.selectRows.push(row.id)
              }
            }
          })
        }
        const exist = selection.findIndex((val) => {
          return val.id === row.id
        }) // exist为-1是取消选择
        if (exist === -1) {
          const index = state.selectRows.findIndex((val) => {
            return val === row.id
          })
          if (index !== -1) {
            state.selectRows.splice(index, 1)
          }
        }
      }
      const selectAll = (selection) => {
        if (selection.length > 0) {
          selection.forEach((row) => {
            if (row) {
              if (state.selectRows.indexOf(row.id) === -1) {
                state.selectRows.push(row.id)
              }
            }
          })
        } else {
          state.list.forEach((item) => {
            state.selectRows.splice(
              state.selectRows.findIndex((val) => {
                return val === item.id
              }),
              1
            )
          })
        }
      }
  
      const emailFilter = (val) => {
        if (val.email !== undefined && val.email !== '' && val.email !== null) {
          let re = val.email
          re = aes.decrypt(
            Base64.decode(val.email),
            aes.rightPad(val.username + '#17mail', 32, aes.keyM)
          )
          const reg = /^(.{3}).*(.{3})$/
          return re.replace(reg, '$1****$2')
        } else {
          return '--'
        }
      }
      const validForbid = (value) => {
        value = value
          .replace(
            /[`~@#$%^&*-+=<>?"{}|;'\\[\]~！：（）·，。【】,.\\/\-_()!@#￥%……&*——+={}|《》？“”、；‘’、]/g,
            ''
          )
          .replace(/\s/g, '')
        return value
      }
      const roleFilter = (roles) => {
        var roleStr = ''
        if (roles === null || roles === '' || roles === undefined) {
          roles = '--'
        } else {
          if (roles.length !== 0) {
            for (var i = 0; i < roles.length; i++) {
              var item = roles[i]
              if (i !== roles.length - 1) {
                roleStr += item + ' | '
              } else {
                roleStr += item
              }
            }
          } else {
            roleStr = '--'
          }
        }
        return roleStr
      }
      const checkSelect = (row) => {
        let isChecked = true
      //   if (row.username === 'admin' || row.id === 1) {
      //     // 判断里面是否存在某个参数
      //     isChecked = false
      //   } else {
      //     isChecked = true
      //   }
        return isChecked
      }
      const handleEdit = (row) => {
        if (row.id) {
          state['editRef'].showEdit(row)
        } else {
          state['editRef'].showEdit()
        }
      }
      const handleDelete = (row) => {
        if (row.id) {
          ElMessageBox.confirm('你确定要删除当前项吗',  'Confirm').then(async()=>{
            console.log("~~~~~~~~~~~~~~~~~~~~ininininin")
            const { msg } = await delUser({ ids: row.id })
            ElMessage.success(msg)
            deletefetchData()
          })
        } else {
          if (state.selectRows.length > 0) {
            const ids = state.selectRows.join(',')
            ElMessageBox.confirm('你确定要删除选中项吗', null).then( async () => {
              const { msg } = await delUser({ ids: ids })
              ElMessage.success(msg)
              deletefetchData()
            })
          } else {
            ElMessage.error('未选中任何行')
          }
        }
      }
 
      const deletefetchData = () => {
      //   // 为了在删除最后一页的最后一条数据时能成功跳转回最后一页的上一页
      //   const totalPage = Math.ceil(
      //     (state.total - 1) / state.queryForm.pageSize
      //   ) // 总页数
      //   state.queryForm.page =
      //     state.queryForm.page > totalPage ? totalPage : state.queryForm.page
      //   state.queryForm.page =
      //     state.queryForm.page < 1 ? 1 : state.queryForm.page
      //   state.multipleTableRef.clearSelection()
      //   fetchData()
      }
      const handleSizeChange = (val) => {
        state.queryForm.pageSize = val
        fetchData()
      }
      const handleCurrentChange = (val) => {
        state.queryForm.page = val
        fetchData()
      }
      const queryData = () => {
        state.queryForm.page = 1
        state.selectRows = []
      //   state.multipleTableRef.clearSelection()
        fetchData()
      }
      const fetchData = async () => {
        state.listLoading = true
        state.list = []
        const {
          data: { items, total },
        } = await getUserList(state.queryForm)
        state.list = items
        state.total = total
        state.listLoading = false
        //记忆分页相关
      //   state.multipleTableRef.clearSelection()
      //   if (state.selectRows.length > 0) {
      //     for (let i = 0; i < state.list.length; i++) {
      //       for (let j = 0; j < state.selectRows.length; j++) {
      //         if (state.list[i].id === state.selectRows[j]) {
      //           state.multipleTableRef.toggleRowSelection(state.list[i])
      //         }
      //       }
      //     }
      //   }
      }

      onMounted(() => {
        getAllDept()
      //   if (hasPermission(['user:view'])) {
          fetchData()
      //   }
      })

      return {
        ...toRefs(state),
        handleEdit,
        handleDelete,
        handleSizeChange,
        handleCurrentChange,
        queryData,
        fetchData,
        Delete,
        Plus,
        Search,
        selSingle,
        selectAll,
        emailFilter,
        roleFilter,
        checkSelect,
        validForbid,
      }
    },
  })
</script>
<style lang="scss">
svg.icon.listIcon {
  width: 24px;
  line-height: 24px;
  height: 24px;
}
vab-query-form {
  text-align: left;
  display: flex;
  justify-content: space-between;
}
.el-table .cell{
  height:24px;
}
.el-pagination{
  justify-content: center;
  margin-top:30px;
}
</style>